﻿using System.Text;

namespace Jayden.Dll.Core.IO
{
	public class DebuggerStream : ProxyStream
	{

		private System.IO.TextWriter m_TextWriter;

		private int m_ReadCallCount;
		private bool m_ReadDebug = true;

		public DebuggerStream(System.IO.Stream stream, string filepath)
			: base(stream)
		{
			m_TextWriter = new System.IO.StreamWriter(filepath);
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			m_TextWriter.Dispose();
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			int read = m_Stream.Read(buffer, offset, count);
			if (m_ReadDebug)
			{
				m_ReadCallCount++;
				m_TextWriter.WriteLine(string.Format("Read has been called for the {4} time (buffer={0}; offset={1}; count={2};) return value is {3}", buffer, offset, count, read, m_ReadCallCount));
				if (read > 0)
				{
					StringBuilder builder = new StringBuilder();
					builder.AppendLine("Datas=");
					for (int c = 0; c < read; c++)
						builder.AppendLine(buffer[offset + c].ToString("X2"));
					m_TextWriter.Write(builder.ToString());
				}
			}
			return read;
		}
	}
}
